package com.quktzhuanka.app.adapter;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.JdDetailsActivity;
import com.quktzhuanka.app.bean.JdGoodsResp;
import com.quktzhuanka.app.bean.JdOrderBean;
import com.quktzhuanka.app.common.T;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.widget.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;
/**
 * Created by yohn on 2018/9/19.
 */

public class JdOrderNewAdapter extends BaseAdapter {
    private Context context;
    private List<JdOrderBean> dataList = new ArrayList<>();
    DecimalFormat df = new DecimalFormat("0.00");
    private LoadingDialog loadingDialog;
    public JdOrderNewAdapter(Context context) {
        this.context = context;
        loadingDialog= LoadingDialog.createDialog(context);
        loadingDialog.setMessage("查询中...");
        loadingDialog.setCanceledOnTouchOutside(false);
    }

    public void setData(List<JdOrderBean> dataList) {
        if (dataList == null) {
            this.dataList = new ArrayList<>();
        } else {
            this.dataList = dataList;
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_new, null);
            holder.tv_name =  convertView.findViewById(R.id.tv_name);
            holder.tv_stu = convertView.findViewById(R.id.tv_stu);
            holder.title_child =  convertView.findViewById(R.id.title_child);
            holder.tv_date =convertView.findViewById(R.id.tv_date);
            holder.tv_one =  convertView.findViewById(R.id.tv_one);
            holder.tv_two = convertView.findViewById(R.id.tv_two);
            holder.txt_copy1 = (TextView) convertView.findViewById(R.id.txt_copy1);
            holder.txt_code = convertView.findViewById(R.id.order_num);
            holder.tv_three =  convertView.findViewById(R.id.tv_three);
            holder.shop_image = convertView.findViewById(R.id.shop_image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
       final JdOrderBean model = dataList.get(position);
        holder.tv_name.setText("");
        if ("18".equalsIgnoreCase(model.getOrder_status())) {
            holder.tv_stu.setText("已结算");
        } else if ("16".equalsIgnoreCase(model.getOrder_status())) {
            holder.tv_stu.setText("已付款");
        } else if ("15".equalsIgnoreCase(model.getOrder_status())) {
            holder.tv_stu.setText("待付款");
        } else if(!"17".equalsIgnoreCase(model.getOrder_status())){
            holder.tv_stu.setText("失效");
        }
        holder.txt_code.setText("订单号:"+model.getOrder_sn());
        holder.title_child.setText(model.getGoods_name());
        holder.tv_date.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.valueOf(model.getOrder_time()))));
        if (model.getCommission() != null&&model.getCommissionRate()!=null)
            holder.tv_one.setText(df.format(Double.valueOf(Float.valueOf(model.getCommission()))));
        if (model.getPay_price() != null)
            holder.tv_two.setText(model.getPay_price());
        if (model.getGoods_img() != null && model.getGoods_img().startsWith("http")) {
            Glide.with(context).load(model.getGoods_img()).dontAnimate().into(holder.shop_image);
        } else {
            Glide.with(context).load(Constants.APP_IP + model.getGoods_img()).placeholder(R.drawable.no_banner).dontAnimate().into(holder.shop_image);
        }
        holder.txt_copy1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(model.getOrder_sn());
                T.showShort(context, "订单号已复制");
            }
        });
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getJdGoodsRequest(dataList.get(position).getSkuid());
            }
        });
        return convertView;
    }
    /**
     * @属性:获取京东推送商品详情
     * @开发者:wmm
     * @时间:2018/12/11 9:50
     */
    private void getJdGoodsRequest(String id) {

        String SERVER_URL = "http://api-gw.haojingke.com/index.php/v1/api/jd/goodsdetail";
        RequestParams params = new RequestParams();
        params.put("apikey",Constants.jd_hjk_appikey);
        params.put("goods_id",id);
        params.put("isdetail",1);
        params.put("isCoupon",1);

        HttpUtils.post(SERVER_URL, params, new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {


                    JSONObject data = new JSONObject(responseString);
                    if(data.optInt("status_code") == 200){
                        JdGoodsResp jdGoodsResp =  new Gson().fromJson(String.valueOf(data.getJSONObject("data")),JdGoodsResp.class) ;

                        handlers.sendEmptyMessage(1);
                        Intent intent = new Intent(context, JdDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("goods", jdGoodsResp);
                        intent.putExtra("goods", bundle);
                        context.startActivity(intent);
                    }else{
                        handlers.sendEmptyMessage(0);
                        return;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });



//        String SERVER_URL = "https://router.jd.com/api";
//        String appKey = Constants.jdappKey;
//        String appSecret = Constants.jdclient_secret;
//        String accessToken = "";
//        final JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
//        final UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
//        final GoodsReq goodsReq = new GoodsReq();
//        goodsReq.setSkuIds(new Long[]{Long.valueOf(id)});
//        goodsReq.setPageSize(6);
//        goodsReq.setPageIndex(1);
//        request.setGoodsReqDTO(goodsReq);
//        loadingDialog.show();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    UnionOpenGoodsQueryResponse response = client.execute(request);
//
//                    if (response.getData() == null) {
//                        handlers.sendEmptyMessage(0);
//                        return;
//                    }
//                    if (response.getData().length <= 0) {
//                        handlers.sendEmptyMessage(0);
//                        return;
//                    }
//                    try {
//                        handlers.sendEmptyMessage(1);
//                        Intent intent = new Intent(context, JdDetailsActivity.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("goods", response.getData()[0]);
//                        intent.putExtra("goods", bundle);
//                        context.startActivity(intent);
//                    }catch (Exception e){
//                    }
//                } catch (JdException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }
    private Handler handlers= new Handler() {
        @Override
        public void handleMessage(Message msg) {
            loadingDialog.dismiss();
            if(msg.what==1){
            }else {
                T.showShort(context,"暂未查到该商品，或已下架");
            }
            super.handleMessage(msg);
        }
    };
    // 声明缓存类
    static class ViewHolder {
        TextView tv_name, tv_date, title_child, tv_stu, tv_one, tv_two, tv_three,txt_code,txt_copy1;//值
        ImageView shop_image;//
    }
}
